from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
import logging
from userServer.codeApi import verify_code
from userServer.dao.UserInfoDao import registerdao, logindao, updatepwddao, logoutdao, getUserId, getUserIsDelete, findPassworddao
from userServer.models import UserInfo

# 初始化日志记录器
logger = logging.getLogger(__name__)
@csrf_exempt
def login(request):
    """用户登录接口（包含详细日志记录）"""
    logger.info(f"[Login] 收到请求，方法: {request.method}")

    if request.method != 'POST':
        logger.warning("[Login] 非法请求方法")
        return JsonResponse({"success": False, "message": "仅支持POST请求"}, status=405)

    try:
        # 解析请求体
        request_data = json.loads(request.body)
        data = request_data.get('getData', {})
        username = data.get('username')
        password = data.get('password')  # 注意：实际密码不应记录在日志中

        logger.debug(f"[Login] 原始请求数据: {data}")  # 生产环境应关闭
        logger.info(f"[Login] 尝试登录用户: {username}")

        if not username or not password:
            logger.warning(f"[Login] 参数缺失 username:{username} password:****")
            return JsonResponse({"success": False, "message": "缺少用户名或密码"}, status=400)

        # 检查用户状态
        if getUserIsDelete(username):
            logger.warning(f"[Login] 尝试登录已注销用户: {username}")
            return JsonResponse({
                "success": False,
                "message": "登录失败",
                "error": "用户已注销"
            }, status=403)

        # 验证登录凭证
        login_result = logindao(username, password)
        if login_result:
            user_id = getUserId(username)
            logger.info(f"[Login] 登录成功 user_id:{user_id}")

            # 设置会话
            request.session['user_id'] = user_id
            request.session.set_expiry(60 * 60 * 24)
            logger.debug(f"[Login] 会话设置完成，session_key: {request.session.session_key}")

            return JsonResponse({
                "success": True,
                "message": "登录成功",
                "data": {"userId": user_id}
            }, status=200)
        else:
            logger.warning(f"[Login] 登录失败 username:{username} 原因:凭证无效")
            request.session.flush()
            return JsonResponse({
                "success": False,
                "message": "登录失败",
                "error": "用户名或密码错误"
            }, status=401)

    except json.JSONDecodeError as e:
        logger.error(f"[Login] JSON解析失败 原始数据: {request.body} 错误: {str(e)}")
        return JsonResponse({"success": False, "message": "无效的JSON格式"}, status=400)

    except Exception as e:
        logger.exception(f"[Login] 系统异常 用户名:{username} 错误详情:")
        return JsonResponse({
            "success": False,
            "message": "服务器内部错误",
            "error": str(e)
        }, status=500)
@csrf_exempt
def list(request):
    """获取用户列表"""
    logger.info(f"[User List] 收到请求，方法: {request.method}")

    if request.method != 'GET':
        logger.warning("[User List] 非法请求方法")
        return HttpResponse('list bye', status=405)

    try:
        userList = UserInfo.objects.all()
        userListJson = []
        for user in userList:
            userListJson.append({
                "id": str(user.id),
                "username": user.username,
                "password": user.password,  # 注意：生产环境应避免返回密码
                "email": user.email,
                "is_vip": str(user.is_vip),
                "create_time": str(user.create_time),
                "update_time": str(user.update_time),
                "is_delete": str(user.is_delete),
                "points_balance": str(user.points_balance)
            })

        logger.info(f"[User List] 成功返回用户列表，数量: {len(userListJson)}")
        return JsonResponse(userListJson, safe=False, status=200)

    except Exception as e:
        logger.exception(f"[User List] 系统异常 错误详情:")
        return HttpResponse("服务器内部错误", status=500)


@csrf_exempt
def register(request):
    """用户注册接口"""
    logger.info(f"[Register] 收到请求，方法: {request.method}")

    if request.method != 'POST':
        logger.warning("[Register] 非法请求方法")
        return HttpResponse('register bye', status=405)

    try:
        data = json.loads(request.body).get("getData")
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
        code = data.get('code')
        code_type = data.get('type')

        logger.info(f"[Register] 尝试注册用户: {username}, 邮箱: {email}")

        # 验证码校验
        session_code = request.session.get(code_type + 'code')
        session_code_expiry = request.session.get(code_type + 'code_expiry')
        code_verify_result = verify_code(code, session_code, session_code_expiry)

        if not code_verify_result:
            logger.warning(f"[Register] 验证码验证失败 用户: {username}")
            return code_verify_result

        # 执行注册
        try:
            registerdao(username, password, email)
            user_id = getUserId(username)
            logger.info(f"[Register] 注册成功 user_id: {user_id}")

            return JsonResponse({
                "success": "true",
                "message": "注册成功",
                "data": {"userId": str(user_id)}
            }, status=200)

        except Exception as e:
            error_msg = "用户名已存在" if "UNIQUE constraint failed" in str(e) else "未知错误"
            logger.error(f"[Register] 注册失败 用户: {username} 错误: {error_msg}")
            return JsonResponse({
                "success": "false",
                "message": "注册失败",
                "error": error_msg
            }, status=422)

    except json.JSONDecodeError as e:
        logger.error(f"[Register] JSON解析失败 原始数据: {request.body} 错误: {str(e)}")
        return JsonResponse({"success": "false", "message": "无效的JSON格式"}, status=400)

    except Exception as e:
        logger.exception(f"[Register] 系统异常 错误详情:")
        return JsonResponse({"success": "false", "message": "服务器内部错误"}, status=500)


@csrf_exempt
def updatepwd(request):
    """修改密码接口"""
    logger.info(f"[Update Password] 收到请求，方法: {request.method}")

    if request.method != 'POST':
        logger.warning("[Update Password] 非法请求方法")
        return HttpResponse('updatepwd bye', status=405)

    try:
        username = request.POST.get('username')
        old_password = request.POST.get('oldPassword')
        new_password = request.POST.get('newPassword')

        logger.info(f"[Update Password] 尝试修改密码 用户: {username}")

        if updatepwddao(username, old_password, new_password):
            logger.info(f"[Update Password] 密码修改成功 用户: {username}")
            return HttpResponse("修改成功", status=200)
        else:
            logger.warning(f"[Update Password] 密码修改失败 用户: {username} 原因: 原密码错误")
            return HttpResponse("修改失败: 原密码错误", status=401)

    except Exception as e:
        logger.exception(f"[Update Password] 系统异常 用户: {username} 错误详情:")
        return HttpResponse("服务器内部错误", status=500)


@csrf_exempt
def logout(request):
    """用户注销接口"""
    logger.info(f"[Logout] 收到请求，方法: {request.method}")

    if request.method != 'POST':
        logger.warning("[Logout] 非法请求方法")
        return HttpResponse('logout bye', status=405)

    try:
        username = request.POST.get('username')
        logger.info(f"[Logout] 尝试注销用户: {username}")

        if logoutdao(username):
            logger.info(f"[Logout] 注销成功 用户: {username}")
            return HttpResponse("注销成功", status=200)
        else:
            logger.warning(f"[Logout] 注销失败 用户: {username}")
            return HttpResponse("注销失败", status=400)

    except Exception as e:
        logger.exception(f"[Logout] 系统异常 用户: {username} 错误详情:")
        return HttpResponse("服务器内部错误", status=500)


@csrf_exempt
def checkUser(request):
    """检查用户是否存在"""
    logger.info(f"[Check User] 收到请求，方法: {request.method}")

    if request.method != 'POST':
        logger.warning("[Check User] 非法请求方法")
        return HttpResponse('checkUser bye', status=405)

    try:
        username = request.POST.get('username')
        logger.info(f"[Check User] 检查用户是否存在: {username}")

        exists = UserInfo.objects.filter(username=username).exists()
        logger.debug(f"[Check User] 用户存在状态: {exists}")
        return JsonResponse(exists, safe=False, status=200)

    except Exception as e:
        logger.exception(f"[Check User] 系统异常 错误详情:")
        return HttpResponse("服务器内部错误", status=500)


@csrf_exempt
def findPassword(request):
    """找回密码接口"""
    logger.info(f"[Find Password] 收到请求，方法: {request.method}")

    if request.method != 'POST':
        logger.warning("[Find Password] 非法请求方法")
        return HttpResponse('findPassword bye', status=405)
    try:
        data = json.loads(request.body).get('data')
        username = data.get('username')
        email = data.get('email')
        code = data.get('code')
        code_type = data.get('type')
        new_password = data.get('newPassword')

        logger.info(f"[Find Password] 尝试找回密码 用户: {username}")

        # 验证码校验
        code_verify_result = verify_code(request, code_type, code)
        if not code_verify_result:
            logger.warning(f"[Find Password] 验证码验证失败 用户: {username}")
            return code_verify_result

        # 执行密码修改
        if findPassworddao(username, email, new_password):
            logger.info(f"[Find Password] 密码修改成功 用户: {username}")
            return JsonResponse({
                "success": "true",
                "message": "修改成功"
            }, status=200)
        else:
            logger.warning(f"[Find Password] 密码修改失败 用户: {username} 原因: 用户名或邮箱不正确")
            return JsonResponse({
                "success": "false",
                "message": "修改失败",
                "error": "用户名或邮箱不正确"
            }, status=422)

    except json.JSONDecodeError as e:
        logger.error(f"[Find Password] JSON解析失败 原始数据: {request.body} 错误: {str(e)}")
        return JsonResponse({"success": "false", "message": "无效的JSON格式"}, status=400)

    except Exception as e:
        logger.exception(f"[Find Password] 系统异常 错误详情:")
        return JsonResponse({"success": "false", "message": "服务器内部错误"}, status=500)